import React, { Component } from 'react'
// import axios from 'axios'
import PubSub from 'pubsub-js'

export default class Search extends Component {
  
  search = async () => {

    PubSub.publish('atguigu', {name: 'tom', age: 18})

    // 获取用户输入(连续解构赋值+重命名)
    const {keyWordElement: {value:keyWord}} = this
    // 发送请求前通知List更新状态
    // this.props.updateAppState({isFirst: false, isLoading: true})
    PubSub.publish('atguigu', {isFirst: false, isLoading: true})
    // 发送网络请求--使用axios发送
    // axios.get(`http://localhost:3000/api1/search/users2?q=${keyWord}`).then(
    //   response => {
    //     // 请求成功后通知List更新状态
    //     // this.props.updateAppState({isLoading: false, users: response.data.items})
    //     PubSub.publish('atguigu', {isLoading: false, users: response.data.items})
    //   },
    //   error => {
    //     // 请求失败后通知List更新状态
    //     // this.props.updateAppState({isLoading: false, err: error.message})
    //     PubSub.publish('atguigu', {isLoading: false, err: error.message})
    //   }
    // )

    // 发送网络请求-fetch发送(为优化)
    // fetch(`http://localhost:3000/api1/search/users2?q=${keyWord}`).then(
    //   response => {
    //     console.log('成功', response)
    //     return response.json()
    //   },
    //   error => {
    //     console.log('失败', error)
    //     return new Promise(() => {})
    //   }
    // ).then(
    //   response => {
    //     console.log('获取数据成功了', response)
    //   },
    //   error => {
    //     console.log('获取数据失败了', error)
    //   }
    // )
    try {
      const response = await fetch(`http://localhost:3000/api1/search/users2?q=${keyWord}`)
      const data = await response.json()
      PubSub.publish('atguigu', {isLoading: false, users: data.items})
      console.log(data)
    } catch (error) {
      console.log('请求出错', error)
      PubSub.publish('atguigu', {isLoading: false, err: error.message})
    }
    
    

  }
  
  render() {
    return ( 
      <section className="jumbotron">
        <h3 className="jumbotron-heading">搜索github用户</h3>
        <div>
          <input type="text" ref={c => this.keyWordElement = c} placeholder="输入关键词点击搜索"/>&nbsp;
          <button onClick={this.search}>搜索</button>
        </div>
      </section>
    )
  }
}
